package middleware

import (
	"net/http"
	"strings"

	"gitee.com/pangxianfei/frame/library/config"
	"gitee.com/pangxianfei/frame/request"
	"gitee.com/pangxianfei/frame/utils/jwt"
	"gitee.com/pangxianfei/saas/paas"
	"gitee.com/pangxianfei/saas/requests"
	"gitee.com/pangxianfei/saas/response"
	"gitee.com/pangxianfei/saas/sysmodel"
)

func TenantMiddle() request.HandlerFunc {
	return func(ctx request.Context) {
		//用户不存在
		if ctx.ScanUserWithJSON() {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorUnauthorized())
			return
		}

		var HeaderToken requests.HeaderToken
		//  推荐使用 ShouldBindHeader 方式获取头参数
		if err := ctx.ShouldBindHeader(&HeaderToken); err != nil {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorUnauthorized())
			return
		}

		if len(HeaderToken.Authorization) < 20 {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorUnauthorized())
			return
		}

		//解释token值
		newJwt := jwt.NewJWT()
		authorization := strings.Split(HeaderToken.Authorization, " ")

		if len(authorization) != 2 && len(authorization[1]) < 20 {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorUnauthorized())
			return
		}

		userClaims, err := newJwt.ParseToken(authorization[1])
		if err != nil {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorUnauthorized())
			return
		}

		//获取用户信息
		platformAdmin := ctx.User().Value().(*sysmdel.PlatformAdmin)
		if platformAdmin == nil && userClaims.TenantId != platformAdmin.TenantId && platformAdmin.TenantId <= 0 {
			ctx.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorUnregisteredTenantAppDb())
			return
		}
		//出始化DB连接
		paas.DB.SetTenantsDb(platformAdmin.TenantId, config.Instance.AppNo.User)
		ctx.Set("AppId", config.Instance.AppNo.User)
		ctx.Set("TenantId", platformAdmin.TenantId)
		ctx.Next()
	}
}
